# 作者: Isearph
# 创建日期: 2025年6月13日
# 作者邮箱: 2665497226@qq.com


import requests
import json


#api地址
url = 'http://t.weather.sojson.com/api/weather/city/'
#读取json文件
city_json_path = r"data/city.json"
f = open(city_json_path, 'rb')
#使用json模块的load方法加载json数据，返回一个字典
dic_cities = json.load(f)
#通过城市的中文获取城市代码
list_cities = list(dic_cities.keys())


def get_weather(city='长春'):
    if not city:
        city = '长春'
    city_code = dic_cities.get(city)

    try:
        response = requests.get(url + city_code)
        d = response.json()

        # 当返回状态码为200，输出天气状况
        if (d['status'] == 200):
            # print(d["cityInfo"]["parent"], d["cityInfo"]["city"])
            # print(d["data"]["forecast"][0]["high"], d["data"]["forecast"][0]["low"])
            # print(d["data"d['status']]["forecast"][0]["type"])
            output = (f'{d["cityInfo"]["parent"]}, {d["cityInfo"]["city"]}',
                      f'{d["data"]["forecast"][0]["high"]}, {d["data"]["forecast"][0]["low"]}',
                      f'{d["data"]["forecast"][0]["type"]}')
        else:
            output = (f'NetError: {d["status"]}', '无天气', '无网络信息')
    except Exception as e:
        print("解析失败：", e)
        output = (f'NetError: 无连接或无地点', '无天气', '无网络信息')

    return output


# print(get_weather())
